using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace LantixLBSServer.Web.DbAccess.Helper
{
    /// <summary>
    /// abstract transaction base
    /// </summary>
    public abstract class TransHelper:ITransHelper
    {
        private IDbTransaction transaction;

        /// <summary>
        /// database helper
        /// </summary>
        protected DbHelper dbHelper;

        /// <summary>
        /// constructor for transaction
        /// </summary>
        public TransHelper()
        {
            Initialize();
            dbHelper.OpenConnection();
            transaction = dbHelper.Connection.BeginTransaction();
        }

        /// <summary>
        /// Initialize DbHelper
        /// </summary>
        protected abstract void Initialize();


        #region ITransHelper Members
        /// <summary>
        ///  Commits the database transaction.
        /// </summary>
        public void Commit()
        {

            if (transaction == null) throw new ArgumentNullException("transaction is null.");
            if (transaction.Connection == null) throw new ArgumentException("The connection is null, please provide an open connection.", "connection");

            transaction.Commit();    
        }

        /// <summary>
        /// Rolls back a transaction from a pending state.
        /// </summary>
        public void RollBack()
        {

            if (transaction == null) throw new ArgumentNullException("transaction is null");
            if (transaction.Connection != null)
            {
                transaction.Rollback();                
            }
        }

        /// <summary>
        /// Get the transaction.
        /// </summary>
        public IDbTransaction Transaction
        {
            get { return transaction; }
        }

        #endregion

        #region IDisposable Members
        /// <summary>
        /// releasing resources.
        /// </summary>
        public void Dispose()
        {
            if (transaction != null)
            {
                if (transaction.Connection != null)
                {
                    transaction.Connection.Dispose();
                }
                transaction.Dispose();
            }
        }

        #endregion
    }
}
